//
//  JXBAdPageView.swift
//  TestSwift
//
//  Created by Eastwood on 15/9/25.
//  Copyright (c) 2015年 chuangmeng. All rights reserved.
//

import UIKit

@objc protocol JXBAdPageViewDelegate{
    
    func setWebImage(imgView:UIImageView,imgUrl:NSString)
}

typealias JXBAdPageCallback=(clickIndex:NSInteger)->Void
typealias Task = (cancel : Bool) -> ()

class JXBAdPageView: UIView,UIScrollViewDelegate {
    
    var myClosure:JXBAdPageCallback?
    var iDisplayTime:NSInteger?
    var bWebImage:Bool?
    var pageControl:UIPageControl?
    var delegate:JXBAdPageViewDelegate?
    
    var indexShow = 0
    var arrImage = [String]()
    var scView:UIScrollView?
    var imgPrev:UIImageView?
    var imgCurrent:UIImageView?
    var imgNext:UIImageView?
    var myTimer:NSTimer?
    var task:Task?
    
    override init(frame: CGRect) {
        super.init(frame:frame)
            self.initUI()
      
    }

    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI()
    {
        scView = UIScrollView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
        scView?.delegate = self
        scView?.pagingEnabled = true
        scView?.bounces = false
        scView?.contentSize = CGSizeMake(self.frame.size.width * 3, self.frame.size.height)
        scView?.showsHorizontalScrollIndicator = false
        scView?.showsVerticalScrollIndicator = false
        self.addSubview(scView!)
        
        var tap = UITapGestureRecognizer(target: self, action: "tapAds")
        scView?.addGestureRecognizer(tap)
        
        imgPrev = UIImageView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
        imgCurrent = UIImageView(frame: CGRectMake(self.frame.size.width, 0, self.frame.size.width, self.frame.size.height))
        imgNext = UIImageView(frame: CGRectMake(2 * self.frame.size.width, 0, self.frame.size.width, self.frame.size.height))
        
        scView?.addSubview(imgPrev!)
        scView?.addSubview(imgCurrent!)
        scView?.addSubview(imgNext!)
        
        pageControl = UIPageControl(frame: CGRectMake(0, self.frame.size.height - 10, self.frame.size.width, 10))
        pageControl?.currentPageIndicatorTintColor = UIColor.redColor()
        pageControl?.pageIndicatorTintColor = UIColor.whiteColor()
        self.addSubview(pageControl!)
        
    }

    /**
    启动函数
    
    :param: imageArr 图片数组
    */
    func startAds(imageArr:NSArray, closure:JXBAdPageCallback)
    {
        if imageArr.count <= 1
        {
            scView?.contentSize = CGSizeMake(self.frame.size.width, self.frame.size.height)
        }
            pageControl?.numberOfPages = imageArr.count
            arrImage = imageArr as! [(String)]
            myClosure = closure
        println(arrImage)
            self.reloadImages()
        
    }
    
    /**
    点击广告
    */
    func tapAds()
    {
        if (myClosure != nil)
        {
            myClosure!(clickIndex: indexShow)
        }
        if (myTimer != nil)
        {
            myTimer?.invalidate()
            cancel(task)
        }
        if iDisplayTime > 0
        {
            self.startTimerPlay()
        }
    }
    
    /**
    *  加载图片顺序
    */
    func reloadImages()
    {
        if indexShow >= arrImage.count
        {
            indexShow = 0
        }
        if indexShow < 0
        {
            indexShow = arrImage.count - 1
        }
        var prev:Int = indexShow - 1
        if prev < 0
        {
            prev = arrImage.count - 1
        }
        var next:Int = indexShow + 1
        if next > arrImage.count - 1
        {
            next = 0
        }
        pageControl?.currentPage = indexShow
        
        var prevImage:NSString = arrImage[prev] as NSString
        var curImage:NSString = arrImage[indexShow] as NSString
        var nextImage:NSString =  arrImage[next] as NSString
        
        if bWebImage == true
        {
            if (delegate != nil)
            {
                delegate?.setWebImage(imgPrev!, imgUrl: prevImage)
                delegate?.setWebImage(imgCurrent!, imgUrl: curImage)
                delegate?.setWebImage(imgNext!, imgUrl: nextImage)
            }
            else
            {
                imgPrev?.image = UIImage(data: NSData(contentsOfURL: NSURL(string: prevImage as String)!)!)
                imgCurrent?.image = UIImage(data: NSData(contentsOfURL: NSURL(string: curImage as String)!)!)
                imgNext?.image = UIImage(data: NSData(contentsOfURL: NSURL(string: nextImage as String)!)!)
                
            }
        }
        else
        {
            imgPrev?.image = UIImage(named: prevImage as String)
            imgCurrent?.image = UIImage(named: curImage as String)
            imgNext?.image = UIImage(named: nextImage as String)

        }
        scView?.scrollRectToVisible(CGRectMake(self.frame.size.width, 0, self.frame.size.width, self.frame.size.height), animated: false)
        if iDisplayTime > 0
        {
            self.startTimerPlay()
        }
    }
    
    /**
    *  切换图片完毕事件
    *
    *  @param scrollView
    */
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        if (myTimer != nil)
        {
            myTimer?.invalidate()
            cancel(task)
        }
        if scrollView.contentOffset.x >= self.frame.size.width * 2
        {
            indexShow++
        }
        else if scrollView.contentOffset.x < self.frame.size.width
        {
            indexShow--
        }
        println(indexShow)
        self.reloadImages()
    }
    
    func startTimerPlay()
    {
        var sec = NSTimeInterval(iDisplayTime!)
     
        myTimer = NSTimer.scheduledTimerWithTimeInterval(sec, target: self, selector: "doImageGoDisplay", userInfo: nil, repeats: false)
        
    }
    
    func doImageGoDisplay()
    {
        scView?.scrollRectToVisible(CGRectMake(self.frame.size.width * 2, 0, self.frame.size.width, self.frame.size.height), animated: true)
        indexShow++
        
       task = delay(0.3, task: { self.reloadImages() })
    }
    
    /**
    延时方法
    
    :param: time 延时时间
    :param: task
    
    :returns:
    */
    func delay(time:NSTimeInterval, task:()->()) ->  Task? {
        
        func dispatch_later(block:()->()) {
            dispatch_after(
                dispatch_time(
                    DISPATCH_TIME_NOW,
                    Int64(time * Double(NSEC_PER_SEC))),
                dispatch_get_main_queue(),
                block)
        }
        
        var closure: dispatch_block_t? = task
        var result: Task?
        
        let delayedClosure: Task = {
            cancel in
            if let internalClosure = closure {
                if (cancel == false) {
                    dispatch_async(dispatch_get_main_queue(), internalClosure);
                }
            }
            closure = nil
            result = nil
        }
        
        result = delayedClosure
        
        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(cancel: false)
            }
        }
        
        return result;
    }
    
    func cancel(task:Task?) {
        task?(cancel: true)
    }
}
